package com.demo.wormhole.autoconfiguration.datasource;

import com.demo.wormhole.core.reflect.WormholeReflectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@ConditionalOnClass({DataSource.class})
@ConditionalOnProperty({"spring.datasource.primary.type"})
@Configuration
public class WormholeDataSourceAutoConfiguration {
    
    @Value("${spring.datasource.primary.type}")
    private String primaryJdbcType;
    
    @Value("${spring.datasource.shadow.type}")
    private String shadowJdbcType;
    
    @ConditionalOnProperty("spring.datasource.primary.type")
    @Bean(name = "primaryDatasource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDatasource() {
        return WormholeReflectUtils.generateObject(primaryJdbcType);
    }
    
    @ConditionalOnProperty("spring.datasource.shadow.type")
    @Bean(name = "shadowDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.shadow")
    public DataSource shadowDatasource() {
        return WormholeReflectUtils.generateObject(shadowJdbcType);
    }
    
}
